-------------------------------------------------------------------------------
-- Design Name: hw3_top.vhd
-- Author: Aaron Baxter
-- Design Overview: Serial to parallel converter for 8 bit data and one bit parity
-- Parity can either be odd or even
-- Produces a 'valid' signal as well as a bad_parity, when data is output

-- Synthesis Results: No warnings 

-- Utilization:
-- Flip Flops: 51
-- LUTs: 85
-- Slices: 49

-- Functionality: Works as specified
-------------------------------------------------------------------------------

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity hw3_top is
	 Port ( 
			clk 	: in  	STD_LOGIC;
			rst 	: in  	STD_LOGIC;
			data	: in  	STD_LOGIC;
			gate 	: in  	STD_LOGIC;
			odd_parity 	: in  	STD_LOGIC;
			
			out_byte		: out  	STD_LOGIC_VECTOR (7 downto 0);
			valid 			: out  	STD_LOGIC;
			bad_parity		: out  	STD_LOGIC
		);
end hw3_top;

architecture Behavioral of hw3_top is


	signal data_in 	: std_logic_vector(7 downto 0);
	signal count 	: integer;
	signal parity 	: std_logic;
	

begin

	process (clk,rst)
	begin
		if rst = '1' then
			data_in		<= (others => '0');
			out_byte	<= (others => '0');
			count		<= 0;
			parity		<= '0';
			valid		<= '0';
			bad_parity <= '0';
		
		elsif rising_edge(clk) then
			if gate = '1' then
			
				data_in <= data_in (6 downto 0) & data; --clock in data
				count <= count + 1;						--inc the count

				if data = '1' then
					parity <= not(parity);				--keep track of the running parity
				end if;

				--once a full message is recieved
				if count = 8 then					
					--this checks the last bit and compairs it to the current parity
					if data = '1' and parity = odd_parity then 
						bad_parity <= '0';
					else
						bad_parity <= '1';
					end if;					
					
					--send the byte out and pulse valid and reset count
					out_byte <= data_in(7 downto 0);
					count 	<= 0;
					valid	<= '1';
				else
					valid	<= '0';	--make sure to put the valid down
				end if;
				
				
			else  --not in the gate so reset everything
				bad_parity <= '0';
				data_in	<= (others => '0');
				count	<= 0;			
				parity	<= '0';
				valid	<= '0';
			end if;
		end if;
	end process;
	
end Behavioral;









